<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <!-- 边界着色 -->
    <script>
      var colorBorder = function (grid, row, col, color) {
        const dirs = [
          [1, 0],
          [0, 1],
          [-1, 0],
          [0, -1]
        ]
        const n = grid.length
        const m = grid[0].length
        const connected = grid[row][col]
        const vis = new Set()
        const border = []
        // 递归遍历连通网格，收集符合边界要求的连通网格
        function dfs(row, col) {
          const idx = row * m + col
          if (vis.has(idx)) return
          vis.add(idx)
          if (
            // 连通网格在矩阵边界上
            row === 0 ||
            col === 0 ||
            row === n - 1 ||
            col === m - 1 ||
            // 连通网格是边界网格
            grid[row - 1][col] !== connected ||
            grid[row + 1][col] !== connected ||
            grid[row][col - 1] !== connected ||
            grid[row][col + 1] !== connected
          ) {
            // 收集边界网格
            border.push([row, col])
          }
          for (const [dx, dy] of dirs) {
            const nx = row + dx
            const ny = col + dy
            if (nx >= 0 && nx < n && ny >= 0 && ny < m && grid[nx][ny] === connected) {
              // 继续收集连通网格边界
              dfs(nx, ny)
            }
          }
        }
        dfs(row, col)
        // 染色
        border.forEach(p => (grid[p[0]][p[1]] = color))
        return grid
      }
      console.log(
        colorBorder(
          [
            [1, 1],
            [1, 2]
          ],
          0,
          0,
          3
        )
      )
    </script>
  </body>
</html>
